<template>
  <div>
    <div class="button-group-css">
      <div class="button-group-search-css">
        <el-input placeholder="项目" style="width: 160px" v-model="datas.project"></el-input>
        <el-input placeholder="号码" style="width: 160px" v-model="datas.phono"></el-input>
        <el-input placeholder="设备标识" style="width: 160px" v-model="datas.claid"></el-input>
        <el-input placeholder="车牌" style="width: 160px" v-model="datas.username"></el-input>
        <el-input placeholder="终端标识" style="width: 160px" v-model="datas.remark"></el-input>
        <el-select v-model="datas.statu" placeholder="状态">
          <el-option label="使用" value="0" />
          <el-option label="未使用" value="1" />
        </el-select>
        <el-button @click="dataLoad" class="el-button el-button--primary"><i class="el-icon-search"></i><span>搜索</span></el-button>
        <el-button @click="dataclean">重置</el-button>
      </div>
      <div class="button-group-edit">
        <el-button type="danger" @click="batch_del_func">批量删除</el-button>
        <el-button type="success" @click="open_add_dialog()"> 添加 </el-button>
        <!-- <el-button @click="datas.xlsx_up_dialog = !datas.xlsx_up_dialog">
            导入
          </el-button> -->
        <!-- <el-button @click="xlsxDow"> 导出 </el-button> -->
      </div>
    </div>

    <div class="table-div-css">
      <el-table :data="datas.tableList" stripe style="width: 100%" show-summary :summary-method="getSummaries" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="60" />
        <el-table-column type="index" label="ID" />
        <el-table-column prop="project" label="项目" />
        <el-table-column prop="phono" label="号码" />
        <el-table-column prop="claid" label="设备标识" />
        <el-table-column prop="username" label="车牌号" />
        <el-table-column prop="remark" label="系统显示标识" />
        <el-table-column prop="statu" label="状态">
          <template #default="scope">
            <span v-if="scope.row.statu == '1'">未使用</span>
            <span v-else-if="scope.row.statu == '0'">已使用</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="260" fixed="right">
          <template #default="scope">
            <el-button type="primary" @click="open_put_dialog(scope.row)">修改</el-button>
            <el-button type="primary" @click="open_show_dialog(scope.row)">查看</el-button>
            <el-button type="danger" @click="del_func(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- #底部分页栏 -->
    <div class="pagination-div-css">
      <el-pagination
        v-model:current-page="datas.page"
        v-model:page-size="datas.pagesize"
        :page-sizes="[10, 20, 30, 50]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="datas.total"
        @size-change="dataLoad"
        @current-change="dataLoad"
      />
    </div>
  </div>
  <!-- #新增数据 -->
  <el-dialog v-model="datas.dialogVisible" :title="datas.title" width="40%">
    <el-form :model="form" :rules="rules" ref="ruleFormRef">
      <el-form-item label="项目:" :label-width="datas.formLabelWidth" prop="project">
        <el-input v-model="form.project" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号:" :label-width="datas.formLabelWidth" prop="phono">
        <el-input v-model="form.phono" autocomplete="off" />
        <!-- <el-select v-model="form.phono" clearable placeholder="请选择">
          <el-option v-for="item in datas.phone_list" :value="item" :label="item"></el-option>
        </el-select> -->
      </el-form-item>
      <el-form-item label="设备标识:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.claid" autocomplete="off" />
      </el-form-item>
      <el-form-item label="车牌:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态:" :label-width="datas.formLabelWidth">
        <el-select v-model="form.statu" clearable placeholder="请选择">
          <el-option label="使用" value="0" />
          <el-option label="未使用" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="系统标识:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.remark" :rows="2" type="textarea" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close_dialog">取消</el-button>
        <el-button v-if="datas.title == '添加数据'" type="primary" @click="add(ruleFormRef)" :disabled="shake_obj.add">添加</el-button>
        <el-button v-if="datas.title == '修改数据信息'" type="primary" @click="put" :disabled="shake_obj.put">修改</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="datas.show_dialog" :title="'查看数据'" width="40%">
    <el-form :disabled="true" :model="form">
      <el-form-item label="项目:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.project" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.phono" autocomplete="off" />
      </el-form-item>
      <el-form-item label="设备标识:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.claid" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.statu" autocomplete="off" />
      </el-form-item>
      <el-form-item label="车牌:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>

      <el-form-item label="系统标识:" :label-width="datas.formLabelWidth">
        <el-input v-model="form.remark" :rows="2" type="textarea" autocomplete="off" />
      </el-form-item>
    </el-form>
  </el-dialog>

  <el-dialog v-model="datas.xlsx_up_dialog" title="批量上传">
    <el-upload drag :action="api_ap1_excel_post_link" multiple :headers="headers" :on-success="xlsxSuccess" :on-error="xlsxError">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽<em>或点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">请上传指定模板的数据 上传后需要一段时间进行处理</div>
      </template>
    </el-upload>
  </el-dialog>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import {
  api_ap2_list_get,
  api_ap2_list_post,
  api_ap2_list_put,
  api_ap2_list_del,
  api_ap2_phone_select_get
  // api_phonomange_excel_post_link,
  // api_phonomange_excel_down_link,
} from '../../../api/api'
import { useRouter } from 'vue-router'
const router = useRouter()
const datas = reactive({
  tableList: [],
  dialogVisible: false,
  show_dialog: false,
  formLabelWidth: '80px',
  title: '',
  page: 1,
  pagesize: 10,
  total: 0,
  select_list: [],
  xlsx_up_dialog: false,
  project: '',
  phono: '',
  claid: '',
  username: '',
  statu: '',
  remark: '',
  phone_list: []
})
const form = reactive({
  project: '',
  phono: '',
  claid: '',
  username: '',
  statu: '',
  remark: '',
  account: ''
})
const rules = reactive({
  project: [{ required: true, message: '项目不能为空', trigger: 'blur' }],
  phono: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ]
})

const statuOptions = reactive([
  { id: 1, label: '已完成', value: 'Completed' },
  { id: 2, label: '未完成', value: 'Unfinished' }
])
//上传文件时附带身份信息
const headers = {
  Authorization: localStorage.getItem('token')
}

//防抖
const shake_obj = reactive({
  add: false,
  put: false
})

const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      // #统计行，列计算
      sums[index] = ' '
      return
    }
    const values = data && data.length && data.map((item) => Number(item[column.property]))
    // #统计行，计算指定列，index == 0（指定字段，从0开始）
    if (values && values.length && !values.every((value) => Number.isNaN(value)) && index == 0) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)}`
    } else {
      //不计算列留空
      sums[index] = ''
    }
  })

  return sums
}

//选中触发的方法
const handleSelectionChange = (val) => {
  //选中触发的方法
  let L = []
  for (let index = 0; index < val.length; index++) {
    const element = val[index]
    L.push(element.id)
  }
  datas.select_list = L
}

const close_dialog = () => {
  //点击弹窗的取消按钮触发的方法
  datas.dialogVisible = false
}

const open_add_dialog = () => {
  //添加添加添加数据的方法
  datas.title = '添加数据'

  form.project = ''
  form.phono = ''
  form.claid = ''
  form.username = ''
  form.statu = ''
  form.remark = ''

  datas.dialogVisible = true
}

const open_put_dialog = (row) => {
  //点击修改触发的方法

  datas.title = '修改数据信息'

  form.id = row.id
  form.project = row.project
  form.phono = row.phono
  form.claid = row.claid
  form.username = row.username
  form.statu = row.statu
  form.remark = row.remark
  form.account = row.account

  datas.dialogVisible = true
}
const open_show_dialog = (row) => {
  //点击修改触发的方法

  form.id = row.id
  form.project = row.project
  form.phono = row.phono
  form.claid = row.claid
  form.username = row.username
  form.statu = row.statu
  form.remark = row.remark

  datas.show_dialog = true
}

const ruleFormRef = ref()

const add = async (formEl) => {
  //向后端提交添加账号数据的方法
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      api_ap2_list_post(form).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success'
          })
          dataLoad()
          close_dialog()
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const put = () => {
  //向后端提交修改数据的方法
  if (shake_obj.put) {
    return
  }
  shake_obj.put = true
  setTimeout(() => {
    shake_obj.put = false
  }, 1000)

  api_ap2_list_put(form).then((res) => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      dataLoad()
      close_dialog()
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

const del_func = (row) => {
  //点击删除按钮触发的方法
  ElMessageBox.confirm(`确定删除?`, '提示', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      let dic = {
        id: row.id
      }
      api_ap2_list_del(dic).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success'
          })
          dataLoad()
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    })
    .catch(() => {})
}

const batch_del_func = () => {
  //批量删除触发方法
  ElMessageBox.confirm(`确定删除选择内容?`, '提示', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      let dic = {
        id: datas.select_list.join(',')
      }
      api_ap2_list_del(dic).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            message: res.data.msg,
            type: 'success'
          })
          dataLoad()
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    })
    .catch(() => {})
}

//上传xlsx成功
const xlsxSuccess = (res) => {
  //批量上传
  if (res.code === 200) {
    ElMessage({
      message: res.msg,
      type: 'success'
    })
    dataLoad()
  } else {
    ElMessage.error(res.msg)
  }
}
//上传xlsx失败
const xlsxError = (err) => {}

const xlsxDow = () => {
  //下载xlsx
  let link = api_ap1_excel_down_link + '?'
  let param = ['project', 'mode', 'name', 'msg', 'remark']
  for (const val of param) {
    link += val + '=' + datas[val] + '&'
  }

  link = link + 'AUTHORIZATION=' + localStorage.getItem('token')

  var a = document.createElement('a')
  a.href = link // 替换为你想要访问的链接地址
  a.click()
}
const dataclean = () => {
  const keyArr = ['pagesize', 'xlsx_up_dialog', 'show_dialog', 'dialogVisible']
  for (let key in datas) {
    if (!keyArr.includes(key)) datas[key] = ''
  }
  dataLoad()
}
const dataLoad = () => {
  //数据加载
  let dic = {
    page: datas.page,
    pagesize: datas.pagesize,
    project: datas.project,
    phono: datas.phono,
    username: datas.username,
    claid: datas.claid,
    statu: datas.statu,
    remark: datas.remark

    // ...datas
  }
  api_ap2_list_get(dic).then((res) => {
    if (res.data.code == 200) {
      console.log(res.data.data.data, 'ta.data.data')
      datas.tableList = res.data.data.data
      datas.total = res.data.data.total
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

// const phone_select_dataLoad = () => {
//   api_ap2_phone_select_get().then((res) => {
//     if (res.data.code == 200) {
//       datas.phone_list = res.data.data
//     } else {
//       ElMessage.error(res.data.msg)
//     }
//   })
// }

//初始加载数据
onMounted(() => {
  dataLoad()
  phone_select_dataLoad()
})
</script>
<style scoped>
.button-group-css {
  display: flex;
  justify-content: space-between;
  flex-direction: column;
}

.button-group-search-css {
  display: flex;
}

.button-group-search-css > .el-input {
  margin-right: 0.25rem;
}

.button-group-edit {
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
}

.table-div-css {
  height: 75vh;
  overflow: auto;
}

.pagination-div-css {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
